//
//  WmcShareWatermarkVM.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/8/10.
//

import RxRelay
import UIKit
import YPBedrock
import SVProgressHUD

class WmcShareWatermarkVM: WmcBaseVM {
    // MARK: 参数

    /// 水印模型
    var watermarkModel: WmcWatermarkDetailModel?

    // MARK: 输出

    /// 水印
    let watermarkRelay: BehaviorRelay<WmcWatermarkDetailModel?> = .init(value: nil)

    // MARK: 其他

    /// 水印图片
    var watermarkPreviewImage: UIImage?

    // MARK: 输入

    func loadData() {
        watermarkRelay.accept(watermarkModel)
    }

    /// 分享
    func share(scene: WmcShareManager.Scene,
               watermarkContentView: WmcWatermarkContentView)
    {
        // 生成水印信息
        guard let watermarkModel = watermarkRelay.value else { return }
        watermarkModel.shareCompatibleAndroidFields()
        guard let watermarkInfo = watermarkModel.toJSON() else { return }
        SVProgressHUD.show()
        // 生成水印图片
        generateWatermarkImage(watermarkContentView) { [weak self] image in
            guard let weakSelf = self else { return }
            // 图片上传
            weakSelf.uploadWatermarkPreviewImage(image, wmId: watermarkModel.wmId) { imageUrl in
                WmcPrint("水印分享预览上传图片地址：\(imageUrl)")
                // 通知服务器
                WmcMediaWatermarkAPI.fetchWatermarkShare(watermarkInfo: watermarkInfo, watermarkUrl: imageUrl).subscribe { value in
                    let wmcImage = WmcImage(url: value.img)
                    // 下载分享预览图
                    wmcImage.loadUIImage { image in
                        SVProgressHUD.dismiss()
                        // 进行分享
                        WmcShareManager.shareLink(value.url, title: value.title, description: value.content, thumbImage: image, scene: scene)
                    } failureBlock: { _ in
                        SVProgressHUD.dismiss()
                    }

                } onError: { err in
                    SVProgressHUD.dismiss()
                } onCompleted: {
                    SVProgressHUD.dismiss()
                } onDisposed: {
                    SVProgressHUD.dismiss()
                }.disposed(by: weakSelf.rx.disposeBag)
            } failureBlock: { // 上传失败
                SVProgressHUD.dismiss()
            }
        }
    }

    // MARK: 复用

    /// 生成水印图片
    func generateWatermarkImage(_ watermarkContentView: WmcWatermarkContentView,
                                successBlock: @escaping YPBlock.OneParam<UIImage>)
    {
        if let watermarkPreviewImage = watermarkPreviewImage {
            successBlock(watermarkPreviewImage)
        } else {
            guard let image = watermarkContentView.yp.screenshot() else { return }
            watermarkPreviewImage = image // 缓存
            successBlock(image)
        }
    }

    /// 上传水印预览图
    func uploadWatermarkPreviewImage(_ image: UIImage,
                                     wmId: Int,
                                     successBlock: @escaping YPBlock.OneParam<String>,
                                     failureBlock: YPBlock.Empty? = nil)
    {
        guard let imageData = image.yp.jpegData else { return }
        var params: WmcUploadFileModel = .init()
        params.entryId = 555574
        params.type = 0
        params.format = "png"
        params.wmId = wmId
        if let uid = WmcLoginManager.shared.yupaoAccountModel?.userId {
            params.uid = uid.yp.int
        }
        WmcUploadManager.uploadFile(data: imageData,
                                    params: params,
                                    completion: { value in
                                        successBlock(value.accessUrl)
                                    }, failure: { _ in
                                        failureBlock?()
                                    })
    }
}
